package org.jeecg.modules.demo.pcl.controller;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.demo.pcl.service.impl.RestfulMesBoardServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
* @Description: RestFul接口-Mes-大屏数据
* @Author: jeecg-boot
* @Date:   2025-01-15
* @Version: V1.0
*/
@Api(tags="RestFul接口-Mes-大屏数据")
@RestController
@RequestMapping("/rest/mesboard")
@Slf4j
public class RestfulMesBoardController{
    @Autowired
    RestfulMesBoardServiceImpl restfulMesBoardService;

    private static OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(300, java.util.concurrent.TimeUnit.SECONDS) // 设置读取超时时间为60秒
            .writeTimeout(300, java.util.concurrent.TimeUnit.SECONDS) // 设置写入超时时间为60秒
            .connectTimeout(300, java.util.concurrent.TimeUnit.SECONDS) // 设置连接超时时间为60秒
            .connectionPool(new ConnectionPool(5, 5, java.util.concurrent.TimeUnit.MINUTES))
            .build();

    public static String getToken() throws IOException {
        client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
                .addFormDataPart("username", "zhangxiyao")
                .addFormDataPart("password", "ixGabmLrElD2UXsdPKZmuu2WztvBTT3VWJm8xFt33DV46MYhNf7HM1549JWNVMQbVfJEcBt8Owur+k2O6rrVOQ==")
                .addFormDataPart("device_id", "43f351bc-20af-304e-9cd8-732620a71eee")
                .build();
        Request request = new Request.Builder()
                .url("http://cccmesgate.magna.global/oauth/oauth/token?client_id=client&client_secret=secret&grant_type=password&source_type=app")
                .method("POST", body)
                .addHeader("Authorization", "bearer")
                .addHeader("Accept-hips-Language", "zh_CN")
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .build();
        Response response = client.newCall(request).execute();

        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        }

        // 解析JSON响应
        String responseBody = response.body().string();
        JsonObject jsonObject = JsonParser.parseString(responseBody).getAsJsonObject();
        String accessToken = jsonObject.get("access_token").getAsString();

        return accessToken;
    }


    /**
     * 机台号查询全量数据
     */
    @ApiOperation(value = "机台号查询全量数据", notes = "机台号查询全量数据")
    @GetMapping(value = "/query")
    public String query(@RequestParam(required = false) String baseUrl,
                                @RequestParam(required = false) String workcellId,
                                HttpServletRequest req) throws IOException {
        // 先获取token并封装在下面的请求内
        String token = getToken();

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        LocalTime startTimeOfDay = LocalTime.MIN;
        LocalTime endTimeOfDay = LocalTime.MAX;

        // 定义URL和查询参数
        baseUrl = "http://cccmesgate.magna.global/ksm-mes/v1/2/hme-timing-diagrams/list/for-ui";

        // 构建完整的URL
        String url = String.format("%s?endTime=%s&startTime=%s&workcellId=%s",
                baseUrl,
                LocalDateTime.of(currentDate, endTimeOfDay).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                LocalDateTime.of(currentDate, startTimeOfDay).format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")),
                workcellId);

//        client = new OkHttpClient().newBuilder()
//                .build();
        Request request = new Request.Builder()
                .url(url)
                .method("GET", null)
                .addHeader("Authorization", "bearer " + token)
                .addHeader("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .addHeader("Accept", " application/json, text/plain, */*")
                .addHeader("Accept-Language", " zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6")
                .addHeader("Connection", " keep-alive")
                .addHeader("Host", " cccmesgate.magna.global")
                .addHeader("Origin", " http://cccmes.magna.global")
                .addHeader("Referer", " http://cccmes.magna.global/")
                .addHeader("User-Agent", " Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.0.0.0 Safari/537.36 Edg/133.0.0.0")
                .build();
        Response response = client.newCall(request).execute();
        if (!response.isSuccessful()) {
            throw new IOException("Unexpected code " + response);
        }

        // 获取响应体字符串
        String responseBody = response.body().string();

        // 打印响应体字符串以便调试
        log.info("Response Body: {}", responseBody);
        return responseBody;
    }

    /**
     * 机台号查询全量数据
     */
    @ApiOperation(value = "机台号查询全量数据", notes = "机台号查询全量数据")
    @GetMapping(value = "/workcell")
    public ResponseEntity<Result<List<RestfulMesBoardServiceImpl.Workcell>>> workcell() throws SQLException {
        Result<List<RestfulMesBoardServiceImpl.Workcell>> result = restfulMesBoardService.getworkcell();

        // 返回结果，状态码为200
        return ResponseEntity.ok(result);
    }
}
